package com.wuda.servlet.admin;


import com.wuda.dao.UserDao;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
@WebServlet("/admin/deleteUser")
public class DeleteUser extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json; charset=utf8");

		int userId = Integer.parseInt(req.getParameter("userId"));

		System.out.println("删除用户：" + userId);
		// 准备返回参数
		int code = 500;
		String msg = "删除失败";
		UserDao userDao = new UserDao();
		boolean success = false;
		try {
			success = userDao.deleteUser(userId);
			if (success) {
				code = 200;
				msg = "删除成功";
			}

			// 返回JSON结果
			JSONObject jsonResult = new JSONObject();
			jsonResult.put("code", code);
			jsonResult.put("msg", msg);

			try (PrintWriter out = resp.getWriter()) {
				out.print(jsonResult);
				out.flush();
			}
		} catch (SQLException | ClassNotFoundException e) {
			throw new RuntimeException(e);
		}


	}

}
